import React, { useState } from 'react';
import styles from '../lyf/NewTalk.module.css';
import { FileOutline, LeftOutline, UserOutline } from 'antd-mobile-icons';
import { Select, Radio, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import robb from '../lyf/img/3.png'
import a from '../lyf/img/4.png'
import b from '../lyf/img/5.png'
import c from '../lyf/img/6.png'
import d from '../lyf/img/7.png'

export default function NewTalk() {
    const navigate = useNavigate();
    const [formData, setFormData] = useState({
        title: '',
        model: 'llama-2',
        checkpoints: ['GPT-6'],
        preferredName: 'KOTO',
        icon: a,
        communicationStyle: 'formal',
        therapyGoal: '降低压力水平',
        isPublic: true
    });
    const [selectedIcon, setSelectedIcon] = useState(a);


    const modelOptions = [
        { value: 'Qwen2.5-VL-72B', label: 'Qwen2.5-VL-72B' },
        { value: 'Qwen2.5-32B', label: 'Qwen2.5-32B' },
        { value: 'claude-2', label: 'Claude 2' },
        { value: 'llama-2', label: 'LLaMA 2' },
        { value: 'palm-2', label: 'PaLM 2' }
    ];

    const checkpointOptions = ['GPT-6', 'LLAMA4', 'PRIVATEGPT', 'GPT-5', 'BABYAGI', 'PALM3'];
    const communicationStyles = ['casual', 'formal', 'fun'];
    const therapyGoals = ['降低压力水平', '改善睡眠质量', '提高自信心', '缓解焦虑'];
    const imgList=[a,b,c,d]

    const handleInputChange = (field, value) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const handleIconSelect = (icon) => {
        setSelectedIcon(icon);
        handleInputChange('icon', icon);
      };

    const handleCheckpointChange = (value) => {
        setFormData(prev => {
            const newCheckpoints = prev.checkpoints.includes(value)
                ? prev.checkpoints.filter(item => item !== value)
                : [...prev.checkpoints, value];
            
            if (newCheckpoints.length > 3) {
                message.warning('最多只能选择3个检查点');
                return prev;
            }
            
            return {
                ...prev,
                checkpoints: newCheckpoints
            };
        });
    };

    const handleSubmit = async () => {
        try {
            const response = await axios.post('http://localhost:3000/conversations', formData);
            
            if (response.data.success) {
                message.success('对话创建成功');
                navigate(`/websoket?conversationId=${response.data.conversationId}`);
            }
        } catch (error) {
            console.error('创建对话失败:', error);
            message.error(error.response?.data?.error || '创建对话失败');
        }
    };

    //清除聊天记录
    const clearConversation = () => {
        const savedConversations = localStorage.getItem('chatConversations');
        const allConversations = savedConversations ? JSON.parse(savedConversations) : {};
        
        delete allConversations[conversationId];
        localStorage.setItem('chatConversations', JSON.stringify(allConversations));
        
        setMessages([{
            role: 'assistant',
            content: '你好！我是弗洛伊德博士AI，有什么可以帮你的吗？',
            time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
        }]);
    };

    return (
        <div className={styles.container}>
            {/* 顶部标题栏 */}
            <div className={styles.header}>
                <div className={styles.backk} onClick={() => navigate('/talk')}>
                    <LeftOutline className={styles.back} />
                </div>
                <p className={styles.title}>新建对话</p>
            </div>

            {/* 主要内容区域 */}
            <div className={styles.content}>
                {/* 主题名称输入框 */}
                <div className={styles.inputGroup}>
                    <label className={styles.label}>主题名称</label>
                    <div className={styles.gg}>
                        <FileOutline fontSize={20} style={{ marginTop: '15px', marginLeft: '20px' }} />
                        <input
                            type="text"
                            className={styles.inputField}
                            placeholder="错误的人生选择，我很难过！"
                            value={formData.title}
                            onChange={(e) => handleInputChange('title', e.target.value)}
                        />
                    </div>
                </div>

                {/* 人工智能模型选择 */}
                <div className={styles.inputGroup}>
                    <label className={styles.label}>人工智能模型</label>
                    <div className={styles.gg} style={{ display: 'flex', alignItems: 'center' }}>
                        <img src={robb} alt="" style={{ width: '30px', height: '30px', marginLeft: '10px' }} />
                        <Select
                            value={formData.model}
                            className={styles.select}
                            options={modelOptions}
                            bordered={false}
                            style={{ width: '100%' }}
                            onChange={(value) => handleInputChange('model', value)}
                            dropdownStyle={{
                                borderRadius: '8px',
                                boxShadow: '0 4px 12px rgba(0,0,0,0.15)'
                            }}
                        />
                    </div>
                </div>

                {/* AI LLM 检查点 */}
                <div className={styles.inputGroup}>
                    <label className={styles.label}>AI LLM 检查点</label>
                    <div className={styles.hint}>最多选择3个</div>

                    <div className={styles.checkboxGroup}>
                        {checkpointOptions.map(option => (
                            <label key={option} className={styles.checkbox}>
                                <Radio
                                    checked={formData.checkpoints.includes(option)}
                                    onChange={() => handleCheckpointChange(option)}
                                >
                                    {option}
                                </Radio>
                            </label>
                        ))}
                    </div>
                </div>

                {/* 首选名称输入框 */}
                <div className={styles.content}>
                    <div className={styles.inputGroup}>
                        <label className={styles.label}>首选名称</label>
                        <div className={styles.gg2}>
                            <UserOutline className={styles.ren} />
                            <input
                                type="text"
                                className={styles.inputField2}
                                placeholder='KOTO'
                                value={formData.preferredName}
                                onChange={(e) => handleInputChange('preferredName', e.target.value)}
                            />
                        </div>
                    </div>

                    {/* 对话图标选择 */}
                    <div className={styles.inputGroup}>
                        <label className={styles.label}>对话图标</label>
                        <div className={styles.iconSelection}>
                            {imgList.map(icon => (
                                <div 
                                    key={icon}
                                    className={`${styles.icon} ${formData.icon === icon ? styles.selected : ''}`}
                                    onClick={() => handleIconSelect(icon)}
                                >
                                    <img src={icon} alt=""/>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* 沟通方式 */}
                    <div className={styles.inputGroup}>
                        <label className={styles.label}>沟通方式</label>
                        <div className={styles.communicationOptions}>
                            {communicationStyles.map(style => (
                                <div 
                                    key={style}
                                    className={`${styles.option} ${formData.communicationStyle === style ? styles.active : ''}`}
                                    onClick={() => handleInputChange('communicationStyle', style)}
                                >
                                    {style === 'casual' ? '随意的' : style === 'formal' ? '正式的' : '乐趣'}
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* 治疗目标 */}
                    <div className={styles.inputGroup}>
                        <label className={styles.label}>治疗目标</label>
                        <Select
                            value={formData.therapyGoal}
                            style={{ width: '100%' }}
                            onChange={(value) => handleInputChange('therapyGoal', value)}
                            options={therapyGoals.map(goal => ({ value: goal, label: goal }))}
                        />
                    </div>

                    {/* 隐私与安全 */}
                    <div className={styles.inputGroup}>
                        <label className={styles.label}>隐私与安全</label>
                        <div className={styles.privacySetting}>
                            <span>{formData.isPublic ? '公开聊天' : '私密聊天'}</span>
                            <label className={styles.switch}>
                                <input 
                                    type="checkbox" 
                                    checked={formData.isPublic}
                                    onChange={(e) => handleInputChange('isPublic', e.target.checked)}
                                />
                                <span className={`${styles.slider} ${styles.round}`}></span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            {/* 底部创建按钮 */}
            <button 
                className={styles.createButton} 
                onClick={handleSubmit}
                disabled={!formData.title || !formData.model}
            >
                创建对话
            </button>
        </div>
    );
}